<script setup lang="ts">
import { request } from '@/api'
import b64toBlob from 'b64-to-blob'
import {
  closeToast,
  showConfirmDialog,
  showLoadingToast,
  showToast,
  type ActionSheetAction,
} from 'vant'
import { onMounted, ref } from 'vue'
const gender = ref('')
const profile = ref<User>({} as User)
// 取消选项
const onCancel = () => {
  showToast('取消')
}
// -------------------- 头像相关 --------------------------
// 弹窗选项
const actions = [{ name: '拍照' }, { name: '相册' }]
const showAvatarPopup = ref(false)
const onSelect = async (item: ActionSheetAction, i: number) => {
  if (i === 0) {
    // 相册上传
    console.log('拍照上传')
  } else if (i === 1) {
    console.log('去相册')
    const res = await jk.pickerPhoto()
    console.log('相册', res)
    // --- 1. base 转 二进制 ----------
    const img = b64toBlob(res, 'image/jpeg')
    console.log(img)
    try {
      // --- 2. 关闭头像选择弹层 --------------
      showAvatarPopup.value = false
      // --- 3. 创建一个转载数据的 FormData 对象 -------------------
      const fd = new FormData()
      // --- 4. 追加数据 ------------
      fd.append('photo', img, Date.now() + '.jpeg')
      console.log('222')
      // --- 5. 调用上传接口， 根据接口文档设置地址和方法， FormData 设置到参数2 即可

      const uploadRes = await request.patch<JkResponse<{ photo: string }>>('/v1_0/user/photo', fd)
      console.log(uploadRes)
      // --- 6. 修改页面显示 , post请求返回头像地址---------
      profile.value.photo = uploadRes.data.data.photo
      // --- 7. 获取保存在鸿蒙缓存中的用户信息
      const user = jk.getUser()
      // --- 8. 修改用户信息头像 为刚刚上传的头像 ---
      user.photo = uploadRes.data.data.photo
      // --- 9. 更新鸿蒙端的用户信息头像数据 ---
      jk.setUser(user)
      // --- 10. 提示用户修改成功 ---
      showToast('上传成功')
    } catch (e) {
      showToast('上传失败')
      console.log(e)
    }
  }
}
// -------------------- 头像相关 --------------------------

// ---------------- 退出登录 ----------------
import { showDialog } from 'vant'
import { useRouter } from 'vue-router'
const showLogoutPopup = () => {
  showConfirmDialog({
    title: '温馨提示',
    message: '确定退出吗？',
  })
    .then(() => {
      console.log('点击了确认退出')
      profile.value = {} as User
      jk.removeToken()
      jk.setUser({} as User)
    })
    .catch(() => {})
}

// --------------- 性别相关 ------------
const showGender = ref(false)
const selectGender = ref<string[]>([])
const columns = [
  { text: '男', value: 0 },
  { text: '女', value: 1 },
]
const onConfirm = async () => {
  profile.value.gender = Number(selectGender.value.join(''))
  console.log(profile.value.gender)
  if (profile.value.gender === 0) {
    gender.value = '男'
  } else if (profile.value.gender === 1) {
    gender.value = '女'
  } else {
    gender.value = ''
  }
  const res = await request.patch<JkResponse<User>>('/v1_0/user/profile', {
    gender: profile.value.gender,
  })
  console.log(res.data.data) // 响应数据为空？
  jk.setUser(profile.value)
  showGender.value = false
}

// -------------- 生日相关 ---------------------
const showBirthday = ref(false)
const currentDate = ref(['2021', '01', '01'])
const minDate = ref(new Date(1999, 0, 1))
const maxDate = ref(new Date(2025, 9, 1))
const onBirthdayConfirm = async () => {
  // console.log(currentDate.value)
  profile.value.birthday = currentDate.value.join('-')
  const res = await request.patch<JkResponse<User>>('/v1_0/user/profile', {
    birthday: profile.value.birthday,
  })
  jk.setUser(profile.value)
  showBirthday.value = false
}
// -------------- 生日相关 ---------------------

// ------------------- 修改昵称和简介 -跳转编辑页 -------
const router = useRouter()
const nicknameEdit = () => {
  router.push('/editName')
}
const infroEdit = () => {
  router.push('/editInfro')
}
// ---------------------------
onMounted(async () => {
  try {
    const res = await request.get<JkResponse<User>>('/v1_0/user/profile')
    console.log(res)
    profile.value = res.data.data
  } catch (e) {
    showToast('请登录')
  }

  console.log(profile.value.gender)
  if (profile.value.gender === 0) {
    gender.value = '男'
  } else if (profile.value.gender === 1) {
    gender.value = '女'
  } else {
    gender.value = ''
  }
  currentDate.value = profile.value.birthday.split('-')
})
</script>

<template>
  <div class="profile-edit-page">
    <!-- 表单部分 -->
    <!-- 1. 头像 -->
    <div class="input" @click="showAvatarPopup = true">
      <p class="title">头像</p>
      <div>
        <img :src="profile.photo" alt="" class="avataricon" />
        <img src="../imgs/arrow-right.png" alt="" class="right" />
      </div>
    </div>
    <!-- 2. 呢称 -->
    <div class="input" @click="nicknameEdit()">
      <p class="title">呢称</p>
      <div class="rightInfo">
        <p class="content">{{ profile.name }}</p>
        <img src="../imgs/arrow-right.png" alt="" class="right" />
      </div>
    </div>
    <!-- 3. 简介 -->
    <div class="input" @click="infroEdit()">
      <p class="title">简介</p>
      <div class="rightInfo">
        <p class="content">{{ profile.intro }}</p>
        <img src="../imgs/arrow-right.png" alt="" class="right" />
      </div>
    </div>
    <!-- 4. 性别 -->
    <div class="genderinput" @click="showGender = true">
      <p class="title">性别</p>
      <div class="rightInfo">
        <p class="content">{{ gender }}</p>
        <img src="../imgs/arrow-right.png" alt="" class="right" />
      </div>
    </div>
    <!-- 5. 生日 -->
    <div class="input" @click="showBirthday = true">
      <p class="title">生日</p>
      <div class="rightInfo">
        <p class="content">{{ profile.birthday }}</p>
        <img src="../imgs/arrow-right.png" alt="" class="right" />
      </div>
    </div>

    <div>
      <van-button round block type="default" class="logout" @click="showLogoutPopup">
        退出登录
      </van-button>
    </div>

    <!--  头像弹层 -->
    <van-action-sheet
      v-model:show="showAvatarPopup"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSelect"
    />
    <!-- 性别弹层 -->
    <van-popup
      v-model:show="showGender"
      position="bottom"
      :style="{ height: '250px', padding: '20px' }"
    >
      <van-picker
        v-model="selectGender"
        title="选择性别"
        :columns="columns"
        option-height="30px"
        @confirm="onConfirm"
        @cancel="showGender = false"
      />
    </van-popup>

    <!-- 生日弹层 -->
    <van-popup v-model:show="showBirthday" position="bottom" :style="{ padding: '50px' }"
      ><van-date-picker
        v-model="currentDate"
        title="选择日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onBirthdayConfirm"
        @cancel="showBirthday = false"
    /></van-popup>
  </div>
</template>

<style lang="css" scoped>
.title {
  font-size: 15px;
}
.input {
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 10px;
  padding-bottom: 10px;
  border-bottom: 1px rgb(238, 230, 230) solid;
  color: rgb(49, 48, 48);
}
.content {
  color: rgb(146, 145, 145);
}
.avataricon {
  width: 30px;
  height: 30px;
  border-radius: 15px;
}
.rightInfo {
  display: flex;
}
.right {
  width: 20px;
  height: 20px;
}
.genderinput {
  background-color: white;
  color: rgb(49, 48, 48);
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 10px;
  padding-bottom: 10px;
  border-bottom: 1px rgb(238, 230, 230) solid;
}
.logout {
  color: red;
  margin-top: 400px;
}
</style>
